package com.hyfrogx.modules.manage.controller.task;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hyfrogx.common.exception.ServiceException;
import com.hyfrogx.common.qcloud.UploadUtils;
import com.hyfrogx.common.utils.R;
import com.hyfrogx.modules.app.entity.User;
import com.hyfrogx.modules.app.service.UserService;
import com.hyfrogx.modules.app.utils.FrogConstant;
import com.hyfrogx.modules.manage.controller.BaseController;
import com.hyfrogx.modules.manage.entity.coin.CoinDetailEntity;
import com.hyfrogx.modules.manage.entity.task.TaskEntity;
import com.hyfrogx.modules.manage.entity.task.TaskRewardEntity;
import com.hyfrogx.modules.manage.service.task.TaskRewardService;
import com.hyfrogx.modules.manage.service.task.TaskService;
import com.hyfrogx.modules.manage.util.ScoreCoinUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
/**
 * @author 罗春杰-技术部
 */
@RestController
@RequestMapping(value = "task")
@Api(value = "TaskController", tags = {"后台-任务控制类"})
public class TaskController extends BaseController {

    @Autowired
    private TaskService taskService;

    @Autowired
    private TaskRewardService rewardService;
    @Autowired
    private UserService userService;

    /**
     * 编辑图片上传
     *
     * @return
     */
    @PostMapping("/uploadimg")
    public R upload(@RequestParam("file") MultipartFile file) {
        String result = null;
        if (file != null) {
            String fileName = UUID.randomUUID().toString() + file.getOriginalFilename()
                    .substring(file.getOriginalFilename()
                            .lastIndexOf("."), file.getOriginalFilename().length());
            result = UploadUtils.upload(UploadUtils.convertFile(file), fileName, FrogConstant.Path.COURSE);
        }
        return R.ok(result);
    }


    /**
     * 新增任务
     *
     * @param
     * @return
     */
    @RequestMapping(value = "create",method = RequestMethod.POST)
    @ApiOperation("新增任务")
    public R createTask(@RequestBody TaskEntity hyTask, @RequestParam String jsonStr) {
        try {
            JSONArray jsonArray = JSONArray.parseArray(jsonStr);
            if (jsonArray.size() <= 0) {
                return R.error("奖项集合必传");
            }
            hyTask.setCreateTime(new Date());
            hyTask.setStatus(1);
            boolean save = taskService.save(hyTask);
            for (int i = 0; i < jsonArray.size(); i++) {
                TaskRewardEntity hyTaskReward = jsonArray.getObject(i, TaskRewardEntity.class);
                hyTaskReward.setCreateTime(new Date());
                hyTaskReward.setTid(hyTask.getId());
                rewardService.save(hyTaskReward);
            }
            if (save == true) {
                return R.ok("新增成功");
            } else {
                return R.error("新增失败");
            }
        } catch (ServiceException e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 编辑任务
     *
     * @param jsonStr
     * @param hyTask
     * @return JSONResult
     */
    @RequestMapping(value = "edit",method =RequestMethod.POST )
    @ApiOperation("编辑任务")
    public R editTask(@RequestBody TaskEntity hyTask, String jsonStr) {
        try {
            JSONArray jsonArray = JSONArray.parseArray(jsonStr);
            if (jsonArray.size() <= 0) {
                return R.error("奖项集合必传");
            }
            // 查询出原有集合,如果有的项不在原有集合中了,把这一项删除
            List<TaskRewardEntity> list = rewardService.list(new QueryWrapper<TaskRewardEntity>().eq("tid", hyTask.getId()));
            Map<Integer, Object> map = new HashMap<Integer, Object>();
            if (list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    map.put(list.get(i).getId(), list.get(i).getId());
                }
            }
            for (int i = 0; i < jsonArray.size(); i++) {
                TaskRewardEntity hyTaskReward = jsonArray.getObject(i, TaskRewardEntity.class);
                if (hyTaskReward.getId() != null) {
                    // 编辑,原来有,新的也有的,把原来的key筛除出去,直至筛除掉所有编辑的,剩下的没id的都是新增，没出现再str中的都是要删除的
                    if (map.containsKey(hyTaskReward.getId())) {
                        map.remove(hyTaskReward.getId());
                    }
                    hyTaskReward.setUpdateTime(new Date());
                    rewardService.updateById(hyTaskReward);
                } else {
                    hyTaskReward.setCreateTime(new Date());
                    hyTaskReward.setTid(hyTask.getId());
                    rewardService.save(hyTaskReward);
                }
            }
            if (map.size() > 0) {
                // 把多余的删除
                for (Map.Entry<Integer, Object> entry : map.entrySet()) {
                    Integer mapKey = entry.getKey();
                    rewardService.removeById(mapKey);
                }
            }
            // 编辑任务主体
            taskService.updateById(hyTask);
            return R.ok("编辑成功");
        } catch (ServiceException e) {
            return R.error(e.getMessage());
        }
    }


    /**
     * 上架下架
     *
     * @param
     * @return
     */
    @RequestMapping(value = "control", method = RequestMethod.POST)
    @ApiOperation("上架下架")
    public R controlStatus(@RequestBody TaskEntity hyTask) {
        if (hyTask.getId() == null) {
            return R.error("ID不能为空");
        }
        try {
            taskService.updateById(hyTask);
            return R.ok("操作成功");
        } catch (ServiceException e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 调用积分系统项目登录接口
     *
     * @param phone
     * @throws IOException
     */
    @RequestMapping(value = "call/login", method = RequestMethod.POST)
    @ApiOperation("调用积分系统登录接口")
    public R callLogin(@RequestParam String phone) throws IOException {
        if (phone == null) {
            return R.error("手机号必传");
        }
        String token = ScoreCoinUtils.getToken(phone);
        return R.ok(token);
    }

    /**
     * 调用积分系统发送积分变动包体
     *
     * @param phone
     * @throws IOException
     */
    @ApiOperation("调用积分系统发送积分变动包体")
    @RequestMapping(value = "call/create", method = RequestMethod.POST)
    public R create(@RequestParam String phone) throws IOException {
        // 1.完善用户信息
        User user = userService.getOne(new QueryWrapper<User>().eq("phone", phone));
        if (user == null) {
            return R.error("用户不存在");
        }
        // 2.创建包体对象
        CoinDetailEntity coin = new CoinDetailEntity();
        coin.setCoin(88L);
        coin.setDesc("完成资讯评论任务");
        coin.setMark("观看资讯");
        coin.setNickname(user.getUsername());
        coin.setTerminal("sever");
        coin.setType("获得");
        // 3.获取该用户token
        String token = ScoreCoinUtils.getToken(phone);
        // 4.发送包体至积分项目[userId + channelCode(积分系统通过token直接获取) + CoinDetailEntity]
        Integer code = ScoreCoinUtils.sendPackage(coin, token);
        return R.ok().put("data", code);
    }
}
